/**
 * 限制input框数字输入，可以输入正数、负数和小树点，禁用E和e
 * demo: v-numberLimit="{min: 1, max: 10}"
 */

// 正数+负数+小数点判断正则
export const numberReg = /^[+-]?[\d]+([\\.][\d]+)?$/;

export default {
  bind: (el, binding, vNode) => {
    const setValue = (val) => {
      if (vNode.componentInstance) {
        vNode.componentInstance.$emit("input", val);
      } else {
        el.value = val;
        el.dispatchEvent(new Event("input"));
      }
    };

    el.handler = () => {
      let element = el;
      if (element.tagName.toLowerCase() !== "input") {
        element = el.getElementsByTagName("input")[0];
      }
      // 正数+负数+小数点判断正则
      if (!numberReg.test(element.value)) {
        element.value = "";
      }
      const { min, max } = binding.value;

      if (min !== undefined && element.value < min) {
        setValue(min);
      }
      if (max !== undefined && element.value > max) {
        setValue(max);
      }
    };
    // 不允许输入e和E，这两个科学计数法字符不会触发change事件
    el.keydownHandler = (e) => {
      e.returnValue = ["e", "E"].includes(e.key) ? false : e.returnValue;
    };
    el.addEventListener("change", el.handler);
    el.addEventListener("keydown", el.keydownHandler);
  },
  unbind: (el) => {
    el.removeEventListener("change", el.handler);
    el.removeEventListener("keydown", el.keydownHandler);
  },
};
